<?php
$a = array();
if($_FILES['pic']['name'] == ''){
    $a['code'] = -1;
    $a['msg'] = '所有项目均为必填项。';
}
/*print_r($_FILES['carPIC']['error']);*/
switch($_FILES['pic']['error']) {
    case 1:// 文件大小超出了服务器的空间大小
        $a['code'] = -1;
        $a['msg'] = '上传文件太大了。';
        break;
    case 2:// 要上传的文件大小超出浏览器限制
        $a['code'] = -1;
        $a['msg'] = '上传文件太大了。';
        break;
    case 3:// 文件仅部分被上传
        $a['code'] = -1;
        $a['msg'] = '文件上传不完整。';
        break;
    case 4:// 没有找到要上传的文件
        $a['code'] = -1;
        $a['msg'] = '没有文件上传。';
        break;
    case 5:// 服务器临时文件夹丢失
        $a['code'] = -1;
        $a['msg'] = '服务器临时文件夹丢失。';
        break;
    case 6:// 文件写入到临时文件夹出错
        $a['code'] = -1;
        $a['msg'] = '文件写入到临时文件夹出错。';
        break;
    default:
        $a['code'] = 0;
}
if($a['code'] == -1){
    echo json_encode($a);
    exit;
}
//程序如果能到这里，说明上传文件正常
//首先判断文件扩展名是否正确
$allowType = array('jpg','jpeg','png','gif');
$fileName = explode(".",$_FILES['pic']['name']);
$exd = strtolower(end($fileName)); //得到扩展名
if(!in_array($exd,$allowType)){
    $a['code'] = -1;
    $a['msg'] = "文件类型出错。只能上传以下文件：".implode("，",$allowType);
    echo json_encode($a);
    exit;
}
//其次，判断文件大小，不超过1MB
if($_FILES['carPIC']['size'] > 1048576){
    $a['code'] = -1;
    $a['msg'] = "文件尺寸不能超过1MB";
    echo json_encode($a);
    exit;
}
$newFileName = uniqid('',true).".$exd";
if(move_uploaded_file($_FILES['pic']['tmp_name'],'./img/'.$newFileName)){
    //说明文件上传成功
    $a['code'] = 200;
    $a['fileName'] = $newFileName;
}
else{
    $a['code'] = -1;
    $a['msg'] = "上传头像失败";
}
echo json_encode($a);
